package pro.ccy.servlet;

import org.apache.commons.lang3.RandomStringUtils;
import pro.ccy.JdbcUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;

@WebServlet(urlPatterns = "/ccysave")
@MultipartConfig(
            //上传的文件保存的具体位置
                 location = "E:/upload-images",
            //最大支持的文件上限（单位：字节）
                 maxFileSize =100*1024*1024,
            //最大支持的请求上限（单位：字节），要求：maxRequestSize>=maxFile
                 maxRequestSize = 100*1024*1024)
public class GoodsSaveServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("n");
        String price = req.getParameter("p");
        String id = req.getParameter("id");
        if (id != null && !"null".equals(id)) {
            // 存在id,执行更新
            String sql = "UPDATE `goods` SET `name`=?,price=? WHERE id=?";
            JdbcUtils.modify(sql,name,price, id);
        }else{
        // 获取来自前端提交的图片文件
        Part image = req.getPart("i");
        // 获取来自前端提交的图片原始名称
        String fileName = image.getSubmittedFileName();
        //将名称以.进行切割
        String[] strings = fileName.split("\\.");
        //获取文件的后缀名
        String suffix = strings[1];
        //为上传的图片设置新名称
        String img = RandomStringUtils.randomAlphabetic(10) + "." + suffix;
        // 将提交的图片文件保存到磁盘
        image.write(img);

        String sql ="INSERT INTO goods (`name`,price,image) VALUES(?,?,?)";
        JdbcUtils.modify(sql,name,price,img);


    }
        resp.sendRedirect("/ccy/goods-list.jsp");
}}

